Iterations

In this tutorial, we shall discuss the Iterations. Topics we covered in the last tutorial:

  • Boolean
  • Comparison  Operators
  • Decision Making in Python:

Iterations:

In normal execution, each statement is executed only once, but in iterations, the output is displayed continuously until the given condition breaks.

Iterations.png

Types of iterations in python:

  • For
  • While

For loop example:

Executes a sentence multiple times. If we want to print all the elements of a list it takes a lot of time to do that. Let us see those in the code.

For loop in jupyter.png

Here ‘num’ is a  variable that we are declaring and say to python that this ‘num’ is an element is a list.

While:

This loop statement checks the condition initially and then continues.

While loop in jupyter.png

Range:

To create a sequence of a very large number of elements becomes difficult many times, so the range is something by using we can create longer numeric sequences.

Range.png

Let us create a list in Jupyter notebook.

List in jupyter notebook.png

List comprehension:

When we assign the elements of the first list to the second list in a modified way of elements, They are two ways of doing such things

  • Normal looping.
  • List comprehension.

Normal Looping:

 X = [ 1, 2 ,3 ,4 ,5 ,6 ]                   # first list whose items should be assigned

Y = [ ]                                              # empty list , where items should be assigned.

for num in X:

            Y.append(num**2)

Y= [ 1, 4 ,9 ,16 , 25 , 36 ] # output of the iteration

List Comprehension.png

List comprehension:

Y= [ num**2 for num in X ]        # List comprehension method for same action.

List Comprehension for same action.png

Topics we will cover in the next tutorial:

  • Function
  • Map and filter
  • lambda
  • Tuple unpacking

Visit the other sections of the Data Science for more information.

Spread knowledge

Leave a Comment

Your email address will not be published. Required fields are marked *